package cn.getech.data.metadata.controller.meta;

import cn.getech.data.intelligence.common.exception.RRException;
import cn.getech.data.intelligence.common.utils.BaseRes;
import cn.getech.data.intelligence.common.utils.DataRes;
import cn.getech.data.intelligence.common.utils.PageUtils;
import cn.getech.data.intelligence.common.utils.R;
import cn.getech.data.intelligence.common.validator.ValidatorUtils;
import cn.getech.data.intelligence.common.validator.group.AddGroup;
import cn.getech.data.metadata.model.excel.CollectionTableFieldExcel;
import cn.getech.data.metadata.model.excel.MyCellWriteHandler;
import cn.getech.data.metadata.model.excel.MySheetWriteHandler;
import cn.getech.data.metadata.model.excel.TableFieldListener;
import cn.getech.data.metadata.model.req.meta.CollectionTaskListReq;
import cn.getech.data.metadata.model.req.meta.CollectionTaskSave;
import cn.getech.data.metadata.model.res.CollectionTaskDetail;
import cn.getech.data.metadata.service.CollectionTaskService;
import cn.getech.system.center.annotation.SysLog;
import cn.getech.system.center.constant.OperationModulesEnum;
import cn.getech.system.center.constant.OperationTypeEnum;
import cn.getech.system.center.constant.module.ModuleEnum;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;


/**
 * @description: 采集任务
 * @author: wangzhaowen：kiss
 * @create: 2020/9/30 11:00
 * @version: 2020/9/30
 **/
@Slf4j
@Api(value = "采集任务", tags = {"采集任务模块"})
@RestController
@RequestMapping("md/task")
public class CollectionTaskController {
    @Autowired
    private CollectionTaskService collectionTaskService;

    @ApiOperation("列表")
    @PostMapping("/list")  // /data-metadata/md/schedule/list
    public R list(@RequestBody CollectionTaskListReq req) {
        ValidatorUtils.validateEntity(req, AddGroup.class);
        PageUtils page = collectionTaskService.selectListPage(req);
        return R.okWithPage(page);
    }

    @ApiOperation("信息")
    @GetMapping("/info/{id}") // /data-metadata/md/schedule/info
    @SysLog(value="任务详情",type= OperationTypeEnum.GETCODE,
            modulesType = OperationModulesEnum.DATAMETADATACODE,platformModuleType = ModuleEnum.METADATA_GATHER_MODULE_CODE)
    public DataRes<CollectionTaskDetail> info(@PathVariable("id") Long id) {
        CollectionTaskDetail collectionTask = collectionTaskService.getDetailById(id);
        return BaseRes.okWithData(collectionTask);
    }

    @ApiOperation("保存")
    @PostMapping("/save")  // /data-metadata/md/schedule/save
    @SysLog(value="保存采集任务",type= OperationTypeEnum.UPDATECODE,
            modulesType = OperationModulesEnum.DATAMETADATACODE,platformModuleType = ModuleEnum.METADATA_GATHER_MODULE_CODE)
    public BaseRes save(@RequestBody CollectionTaskSave req) {
        if (StringUtils.isEmpty(req.getTaskName())) {
            return BaseRes.error("任务名称不能为空");
        }
        if (req.getTaskName().length() > 15) {
            return BaseRes.error("任务名称不能超过15个字符");
        }
        ValidatorUtils.validateEntity(req, AddGroup.class);
        collectionTaskService.saveTask(req.toCollectionTask(),req.getUserGroupNameId());
        return BaseRes.ok();
    }

    @ApiOperation("删除")
    @PostMapping("/delete") // /data-metadata/md/schedule/delete
    @SysLog(value="采集任务删除",type= OperationTypeEnum.DELETECODE,
            modulesType = OperationModulesEnum.DATAMETADATACODE,platformModuleType = ModuleEnum.METADATA_GATHER_MODULE_CODE)

    public BaseRes delete(@RequestBody List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return BaseRes.error("任务id不能为空");
        }
        collectionTaskService.deleteByIds(ids);
        return BaseRes.ok();
    }

    @ApiOperation("导入")
    @PostMapping("/check") // /data-metadata/md/schedule/check
    @SysLog(value="采集任务检测",type= OperationTypeEnum.CHECKCODE,
            modulesType = OperationModulesEnum.DATAMETADATACODE,platformModuleType = ModuleEnum.METADATA_GATHER_MODULE_CODE)

    public BaseRes checkFile(Long id, @RequestParam(value = "file") MultipartFile file) {
        ExcelReader excelReader = null;
        if (id == null) {
            return BaseRes.error("任务id不能为空");
        }
        if (file == null) {
            return BaseRes.error("任务文件不能为空");
        }
        try {
            TableFieldListener tableFieldListener = new TableFieldListener(id, collectionTaskService, true);
            excelReader = EasyExcel.read(file.getInputStream(), CollectionTableFieldExcel.class,
                    tableFieldListener).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            return tableFieldListener.getCheckExcel();
        } catch (RRException e) {
            log.error("导入错误:", e);
            return BaseRes.error(e.getMsg());
        } catch (Exception e) {
            log.error("导入错误:", e);
            if (e.getCause() != null) {
                return BaseRes.error(e.getCause().getMessage());
            } else {
                return BaseRes.error("excel文件解析失败");
            }
        } finally {
            if (excelReader != null) {
                excelReader.finish();
            }
        }

    }

    @ApiOperation("导入")
    @PostMapping("/import") // /data-metadata/md/schedule/import
    @SysLog(value="采集任务导入",type= OperationTypeEnum.RUNCODE,
            modulesType = OperationModulesEnum.DATAMETADATACODE,platformModuleType = ModuleEnum.METADATA_GATHER_MODULE_CODE)

    public BaseRes importFile(Long id, @RequestParam(value = "file") MultipartFile file) {
        ExcelReader excelReader = null;
        if (id == null) {
            return BaseRes.error("任务id不能为空");
        }
        if (file == null) {
            return BaseRes.error("任务文件不能为空");
        }
        try {
            TableFieldListener tableFieldListener = new TableFieldListener(id, collectionTaskService);
            excelReader = EasyExcel.read(file.getInputStream(), CollectionTableFieldExcel.class,
                    tableFieldListener).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            JSONObject res = tableFieldListener.getData();
            if (res.getString("error_log") != null) {
                return BaseRes.error(res.getString("error_log"));
            }
        } catch (RRException e) {
            return BaseRes.error(e.getMsg());
        } catch (Exception e) {
            log.error("导入错误:", e);
            return BaseRes.error("excel文件解析失败");
        } finally {
            if (excelReader != null) {
                excelReader.finish();
            }
        }
        return BaseRes.ok();
    }

    @ApiOperation("下载模板")
    @GetMapping("/temp/file") // /data-metadata/md/schedule/temp/file
    @SysLog(value="采集任务模板下载",type= OperationTypeEnum.DOWNLOADCODE,
            modulesType = OperationModulesEnum.DATAMETADATACODE,platformModuleType = ModuleEnum.METADATA_GATHER_MODULE_CODE)
    public BaseRes tempFile(HttpServletResponse response) {
        String fileName = "模板文件" + System.currentTimeMillis();
        response.setHeader("Content-Type", "application/octet-stream");
        ExcelWriter excelWriter = null;
        try {
            // 清空response
            response.reset();
            fileName = String.format("%s.xlsx", URLEncoder.encode(fileName, "utf-8"));
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("filename", fileName);
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            ServletOutputStream os = response.getOutputStream();
            excelWriter = EasyExcel.write(os,
                    CollectionTableFieldExcel.class)
                    .registerWriteHandler(new MySheetWriteHandler(CollectionTableFieldExcel.class))
                    .registerWriteHandler(new MyCellWriteHandler(CollectionTableFieldExcel.class))
                    .build();
            WriteSheet sheet = EasyExcel.writerSheet().build();
            excelWriter.write(null, sheet).finish();
        } catch (IOException e) {
            return BaseRes.error("模板文件错误");
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
        return null;
    }


}
